package com.itheima.reggie.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;


    /**
     * 提交订单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submitOrders(@RequestBody Orders orders){
        log.info("orders:==>{}",orders);
        orderService.submitOrders(orders);
        return R.success("订单提交成功");
    }



    /**
     * 订单列表分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<IPage<OrdersDto>> userPage(int page, int pageSize){
        log.info("page => {},pageSize => {}", page, pageSize);
        IPage<Orders> pageInfo = new Page<>(page, pageSize);
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", BaseContext.getCurrentId()).orderByDesc("order_time");
        pageInfo = orderService.page(pageInfo, wrapper);
        IPage<OrdersDto> ordersDtoIPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, ordersDtoIPage,"records");
        List<OrdersDto> ordersDtoList = pageInfo.getRecords().stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            Long orderId = item.getId();
            List<OrderDetail> orderDetailList = orderDetailService.list(new QueryWrapper<OrderDetail>().eq("order_id", orderId));
            if (orderDetailList != null && orderDetailList.size() > 0) {
                ordersDto.setOrderDetails(orderDetailList);
            }
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoIPage.setRecords(ordersDtoList);
        return R.success(ordersDtoIPage);
    }

    /**
     * 再来一单
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R<String>again(@RequestBody Orders orders){
        log.info("orders => {}", orders);
        Long userId = BaseContext.getCurrentId();
        orders.setUserId(userId);//设置用户id
        User user = userService.getById(userId);

        //生成一个订单号
        long newOrderId = IdWorker.getId();

        //计算购物车金额
        AtomicInteger amount = new AtomicInteger(0);

        //获得曾经订单的id
        Long oldOrderId = orders.getId();
        Orders order = orderService.getById(oldOrderId);
        order.setId(newOrderId);
        order.setOrderTime(LocalDateTime.now());//下单时间
        order.setCheckoutTime(LocalDateTime.now());//结账时间
        order.setStatus(2);//订单状态 1待付款，2待派送，3已派送，4已完成，5已取消

        //根据订单id查询出对应的订单明细
        List<OrderDetail> orderDetailList = orderDetailService.list(new QueryWrapper<OrderDetail>().eq("order_id", oldOrderId)).stream().map((item)->{
            item.setId(newOrderId);
            item.setOrderId(newOrderId);
            return item;
        }).collect(Collectors.toList());
        //向订单表插入数据 一条数据
        orderService.save(order);
        //向订单明细表插入数据 多条数据
        orderDetailService.saveBatch(orderDetailList);

        return R.success("再来一旦成功");
    }

    /**
     * 后台订单列表条件分页查询
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<IPage<OrdersDto>> page(int page, int pageSize, String number, String beginTime, String endTime){
        log.info("page => {},pageSize => {}, number => {}, beginTime => {}, endTime => {}", page, pageSize, number, beginTime, endTime);
        IPage<Orders> pageInfo = new Page<>(page, pageSize);
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(StringUtils.trim(number)), "number", number);
        if(beginTime != null && endTime != null){
            wrapper.between("order_time", beginTime, endTime);
        }
        wrapper.orderByDesc("order_time");
        pageInfo = orderService.page(pageInfo, wrapper);
        IPage<OrdersDto> ordersDtoIPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, ordersDtoIPage,"records");
        List<OrdersDto> ordersDtoList = pageInfo.getRecords().stream().map((item) -> {
            Long userId = item.getUserId();
            User byId = userService.getById(userId);
            OrdersDto ordersDto = new OrdersDto();
            ordersDto.setUserName(StringUtils.isNotBlank(byId.getName())?byId.getName():byId.getPhone());
            BeanUtils.copyProperties(item, ordersDto);
            Long orderId = item.getId();
            List<OrderDetail> orderDetailList = orderDetailService.list(new QueryWrapper<OrderDetail>().eq("order_id", orderId));
            if (orderDetailList != null && orderDetailList.size() > 0) {
                ordersDto.setOrderDetails(orderDetailList);
            }
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoIPage.setRecords(ordersDtoList);
        return R.success(ordersDtoIPage);
    }

    /**
     * 修改订单配送状态
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> updateStatus(@RequestBody Orders orders){
        log.info("orders => {}", orders);
        orderService.update(new UpdateWrapper<Orders>().eq("id", orders.getId()).set("status", orders.getStatus()));
        return R.success("success");
    }


}
